const express = require('express');
const router = express.Router();
const mysql = require("../../../mysql/db")
const qx = require("../../../utils/qx")
const { localStorage, md5 } = require("../../../utils/require")
const { createToken } = require('../../../utils/jwt');

router.post('/', (req, res) => {
    const { username, password } = req.body;
    mysql.query("SELECT * FROM `admin` where username = ?", username, function(err, rows) {
        if (err) {
            console.log(err);
            return;
        }
        if (rows == "") {
            res.send({ message: "登录名不存在" })
            sqldb(username, "登录失败", "登录名不存在")
        } else {
            let pwd = md5(md5(password).substr(2, 8) + md5(password))
            let sql = "SELECT t.username,t.token,t.datetime,t.nickname FROM `admin` t where username =  ? and password = ?";
            mysql.query(sql, [rows[0].username, pwd], function(err, doc) {
                if (err) {
                    console.log(err);
                    return;
                }
                if (doc == "") {
                    res.send({ message: "密码错误" })
                    sqldb(username, "登录失败", "密码错误")
                } else {
                    let token = createToken({ username });
                    try {
                        mysql.query("update `admin` set  token = ? ,datetime= NOW() where username = ?", [token, username], (err, data) => {})


                        mysql.query("select  id,DATE_FORMAT(datetime,'%Y年%m月%d日 %H:%i:%s') as datetime,username,nickname from `admin` where username = ? ", username, async(err, v) => {
                            let Permission = await qx.pbulic_qx(v[0].id);
                            req.session.users = {
                                id: v[0].id,
                                username: v[0].username,
                                nickname: v[0].nickname,
                                datetime: v[0].datetime
                            }

                            localStorage.setItem('id', v[0].id)
                            sqldb(username, "登录", "登录成功")
                            res.send({
                                code: 200,
                                qx: Permission,
                                message: "登录成功",
                                token: token,
                            })
                        })

                    } catch (error) {
                        res.status(400).send({ message: "失败" })
                    }


                }


            })

        }

    });


    function sqldb(username, typevalue, reasons) {
        let sql = "insert into `general_log` (username,typevalue,reason) values (?,?,?)";
        mysql.query(sql, [username, typevalue, reasons], (err, doc) => {
            if (err) {
                throw err;
            }
        })
    }



});


module.exports = router